import logging
from logging.handlers import RotatingFileHandler
import os


class AppLog:
    _logger = None

    @staticmethod
    def _get_logger(name="app", log_dir="logs"):
        if AppLog._logger is None:
            AppLog._logger = logging.getLogger(name)
            AppLog._logger.setLevel(logging.DEBUG)

            # 创建日志目录
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)

            # 创建 RotatingFileHandler
            log_file = os.path.join(log_dir, f"{name}.log")
            file_handler = RotatingFileHandler(
                log_file, maxBytes=1024 * 1024, backupCount=5
            )
            file_handler.setLevel(logging.DEBUG)

            # 创建 StreamHandler
            stream_handler = logging.StreamHandler()
            stream_handler.setLevel(logging.INFO)

            # 设置日志格式
            formatter = logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            )
            file_handler.setFormatter(formatter)
            stream_handler.setFormatter(formatter)

            # 添加 handlers
            AppLog._logger.addHandler(file_handler)
            AppLog._logger.addHandler(stream_handler)

        return AppLog._logger

    @staticmethod
    def debug(message):
        AppLog._get_logger().debug(message)

    @staticmethod
    def info(message):
        AppLog._get_logger().info(message)

    @staticmethod
    def warning(message):
        AppLog._get_logger().warning(message)

    @staticmethod
    def error(message):
        AppLog._get_logger().error(message)

    @staticmethod
    def critical(message):
        AppLog._get_logger().critical(message)
